import QQMapWX from "../../../libs/qqmap-wx-jssdk.min"
//对参数进行验证
import Schema from "async-validator"

import { reqAddAddress, reqAddressInfo, reqUpdateAddress } from "../../../api/address"

Page({
  // 页面的初始数据
  data: {
    name: "", //收货人
    phone: "", //手机号码
    provinceName: "", //省
    provinceCode: "", //省编码
    cityName: "", //市
    cityCode: "", //市编码
    districtName: "", //区
    districtCode: "", //市编码
    address: "", //详细地址
    fullAddress: "", //完整地址
    isDefault: false //是否设置为默认地址，0为默认，1为不是
  },

  // 保存收货地址
  async saveAddrssForm(event) {
    const { provinceName,cityName,districtName,address, isDefault } = this.data

      const params = {
          ...this.data,
          fullAddress: provinceName + cityName + districtName + address,
          isDefault: isDefault ? 1 : 0
      }

      const { valid } = await this.vaildatorAddress(params)
      if(!valid) return
      
      const res = this.addressId ? await reqUpdateAddress(params) : await reqAddAddress(params)

      if(res.code === 200 ) {
          wx.navigateBack({
              success: () => {
                wx.toast({ title: this.addressId ? '更新收获地址成功' : '新增收货地址成功' })
              }
          })
      }
  },

  // 验证规则函数
  vaildatorAddress(params) {
    // 验证收货人， 只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'

    // 验证手机号，符合中国大陆手机号码格式
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'

    // 创建验证规则
    const rules = {
        name: [
            { required: true, message: '请输入收货人姓名' },
            { pattern: nameRegExp, message: '收货人姓名不合法' }
        ],
        phone: [
            { required: true, message: '请输入收货人手机号码' },
            { pattern: phoneReg, message: '收货人手机号码不合法' }
        ],
        provinceName: { required: true, message: '请选择收货人所在地区' },
        address: { required: true, message: '请填写收货人地址' }
    }

    // 传入验证规则进行实例化
    const validator = new Schema(rules)

    return new Promise((resolve) => {
        validator.validate(params, (errors) => {
            if(errors) {
                wx.toast({ title: errors[0].message })
                resolve({ valid: false })
            } 
            else { 
                resolve({ valid: true })
            }
        })
    })
  },


  // 省市区选择
  onAddressChange(event) {
      const [ provinceName, cityName, districtName ] = event.detail.value
      const [provinceCode, cityCode, districtCode ] = event.detail.code

      this.setData({
        provinceName, 
        cityName, 
        districtName,
        provinceCode, 
        cityCode, 
        districtCode
      })
  },

  async onLocation() {
    //   const res = await wx.getLocation()
    //   console.log(res)

    const { latitude, longitude, name } = await wx.chooseLocation()

    //对地址进行逆解析
    this.qqmapwx.reverseGeocoder({
        location: {
            latitude,
            longitude 
        },

        success: (res) => {
            // 解构获取省市区及行政编码
            const { province, city, district, adcode} = res.result.ad_info

            // 解构获取街道及门牌号
            const { street, street_number } = res.result.address_component

            // 解构获取标准地址信息
            const { standard_address } = res.result.formatted_addresses

            this.setData({
                // 省
                provinceName: province,
                provinceCode: adcode.replace(adcode.substring(2,6), '0000'),

                //市
                cityName: city,
                cityCode: adcode.replace(adcode.substring(4,6), '00'),

                // 区
                districtName: district,
                // 东莞市、中山市、儋州市、嘉峪关市 因其下无区县级，如果有区县，赋值，没有即为空
                districtCode: district && adcode,

                // 详细地址
                address: street + street_number + name, 

                // 完整地址
                fullAddress: standard_address + name
            })
        }
    })
  },

  // 更新相关逻辑函数
  async showAddressInfo(id) {
    // 通过查看id是否存在来判断是否是更新页面
    if(!id) return

    this.addressId = id

    wx.setNavigationBarTitle({
      title: '更新收货地址'
    })

    // 获取需要更新的收货地址详情
    const { data } = await reqAddressInfo(id)
    this.setData( data )
  },

  onLoad(options) {
      //对核心类 QQMapWX 进行实例化
      this.qqmapwx = new QQMapWX({
          key: 'P4ABZ-YT53G-5JWQB-QMNGR-X7MTO-HTFZA',
      })

      this.showAddressInfo(options.id)
  }
})
